package com.api.test;

import java.util.HashMap;
import java.util.Map;

import com.api.request.model.ApiRequestBuilder;

public abstract class AbstractApi implements Api {

	private Map<Class<?>, Object> services = new HashMap<Class<?>, Object>();

	@Override
	public <T> T getService(Class<T> serviceClass) {

		return lazyInitService(serviceClass);
	}

	public <T> T lazyInitService(Class<T> serviceClass) {

		T service = null;

		if (services.containsKey(serviceClass)) {

			@SuppressWarnings("unchecked")
			T apiService = (T) services.get(serviceClass);
			service = apiService;
		} else {
			service = getProxyService(serviceClass);
			services.put(serviceClass, service);
		}
		return service;
	}

	public void signRequest(ApiRequestBuilder request) {
		if (!isLoggedIn()) {
			throw new IllegalStateException("User not logged in");
		}
		request.sign(getAccessKey(), getAccessSecret());
	}

	public <T> T send(ApiRequestBuilder request) throws Exception {
		if (!isLoggedIn()) {
			throw new IllegalStateException("User not logged in");
		}
		request.sign(getAccessKey(), getAccessSecret());
		return request.send();
	}

	protected abstract <T> T getProxyService(Class<T> serviceClass);

}
